package com.hqyj.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hqyj.config.AlipayConfig;
import com.hqyj.config.PayConfig;
import com.hqyj.exception.R;
import com.hqyj.pojo.PayParameter;
import com.hqyj.service.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class AliPayServiceImpl implements AliPayService {

    @Autowired
    PayConfig payConfig;
    @Autowired
    AlipayClient alipayClient;
    @Override
    public R tranPay(PayParameter payParameter) {
        try {
            // 构造请求参数 Json 格式
            Map<String, Object> map = new HashMap<>();
            map.put("out_trade_no", payParameter.getOrderId());
            map.put("total_amount", payParameter.getPayMoney());
            map.put("subject", payParameter.getSubject());
            map.put("body", payParameter.getBody());
            //将请求参数转换成json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String alipayJson = objectMapper.writeValueAsString(map);

            // 设置支付内容，发送请求，返回结果
            AlipayTradePrecreateRequest alipayRequest = new AlipayTradePrecreateRequest();
            alipayRequest.setNotifyUrl(payConfig.getNotifyUrl());
            alipayRequest.setBizContent(alipayJson);
            //获取支付宝支付响应对象
            AlipayTradePrecreateResponse alipayResponse = alipayClient.execute(alipayRequest);
            //响应成功
            if (alipayResponse.isSuccess()) {
                //设置返回前端的二维码付款地址和订单编号
                Map<String, Object> m = new HashMap<>();
                m.put("num",payParameter.getOrderId());
                m.put("url",alipayResponse.getQrCode());
                return R.ok("success",m);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("支付异常");
        }
        return R.error("支付失败");
    }
}
